﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.Areas.WebApi.Controllers;
using HyEduOnline.Entities;
using HyEduOnline.Server.Student;
using HyEduOnline.Server.Common;
using System.IO;
using HyEudOnline.Server.Common;
using HyEduOnline.Server.Teacher;
using HyEduOnline.Server.Admin;

namespace WebSite.Areas.WebApi.Controllers
{
    public class StudentController : StudentsController
    {


        private StudentsDAO studentsDAO = new StudentsDAO();
        private StuPracticeDAO stuPraDAO = new StuPracticeDAO();
        private StuPracticeOptionsDAO optionDAO = new StuPracticeOptionsDAO();
        private StuPracticeListDAO praListDAO = new StuPracticeListDAO();
        private StuPracticeDetailDAO detDAO = new StuPracticeDetailDAO();
        private StuPracticeOptionsDAO selOption = new StuPracticeOptionsDAO();
        /// <summary>
        /// 学生个人信息更新
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="pk"></param>
        /// <returns></returns>
        public int StuUpdate(string name, string value, string pk)
        {
            int id = frontCurrentStu.GetUserID();
            TbStudents temp = StudentsDAO.GetByID(id);
            ClassValueCopier.SetValue(temp, name, value);
            studentsDAO.Update(temp);

            return 0;
        }


        /// <summary>
        /// 修改密码时，验证当前密码
        /// </summary>
        /// <param name="Password"></param>
        /// <returns></returns>
        public int CheckPassword(string Password)
        {
            Password = Utitil.MD5(Password);//加密
            int id = frontCurrentStu.GetUserID();
            TbStudents stu = studentsDAO.GetByID(id);
            if (stu.SPassWord.Equals(Password))
                return 1;//验证成功
            else
                return 0;
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="Password"></param>
        /// <returns></returns>
        public int UpdatePassword(string Password)
        {
            int id = frontCurrentStu.GetUserID();
            TbStudents stu = studentsDAO.GetByID(id);
            if (!string.IsNullOrEmpty(Password))
            {
                stu.SPassWord = Utitil.MD5(Password);
            }           
            studentsDAO.Update(stu);
            return 1;
        }




        /// <summary>
        /// 首页获取公告,邮箱
        /// </summary>
        /// <returns></returns>
        public JsonResult Search()
        {
            int totalCount = 0;  //总的数据记录条数I_NoticesType
            string condition = "I_NoticesType = 0" + "or I_NoticesType=3";//+ FrontUserInfo.GetUserType()
            IList<TbNotices> noticeList = new NoticesDAO().GetByPage(condition, 0, 5, "DSendTime", "DESC", out totalCount);
            condition = "I_IsRead=0 and S_RecNo='" + frontCurrentStu.GetNo() + "'";
            IList<VwEmail> emailList = new VwEmailDAO().GetByPageVW(condition, 0, 5, "DSendTime DESC", out totalCount);
            return Json(
                new
                {
                    noRead = totalCount,
                    notices = noticeList,
                    emails = emailList
                });
        }

        /// <summary>
        /// 获得已考试卷
        /// </summary>
        /// <param name="CourseId"></param>
        /// <returns></returns>
        public JsonResult GetByPaper(int CourseId)
        {
            string courseCode = new DeanCourseDAO().GetByID(CourseId).SCourseCode;
            string condition = "S_CouseCode='" + courseCode + "' and I_StuID=" + frontCurrentStu.GetUserID()
                + " and I_IsRead = 1";
            TList<TbTestScores> list = new TestScoresDAO().getByPageDataBase(0, 20, "ID", condition, out totalCount);
            return Json(new
            {
                Data = list,
                DataCount = totalCount,
            }, JsonRequestBehavior.AllowGet);
        }



        //add 于10.25

        #region 查询该课程下所有对学生公开的试题
        /// <summary>
        /// 查询该课程下所有对学生公开的试题
        /// </summary>
        /// <param name="firstResult"></param>
        /// <param name="pagesize"></param>
        /// <param name="orderBy"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public Object SearchOpenTestLib(int firstResult, int pagesize, string orderBy, string condition)
        {

            int totalCount = 0;
            condition = HttpUtility.UrlDecode(condition);
            condition = condition + "and I_StuOpen=1";
            IList<TbTestLib> userList = new TestLibDAO().getByPageDataBase(firstResult, pagesize, orderBy, condition, out totalCount);
            return this.Json(new
            {
                DataCount = totalCount,
                Data = userList
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 查看每一个试题的具体内容
        /// <summary>
        /// 查看每一个试题的具体内容
        /// </summary>
        /// <param name="testLibId"></param>
        /// <returns></returns>
        public JsonResult ShowDetailTestLib(long testLibId)
        {
            TbTestLib tempList = new TestLibDAO().GetByID(int.Parse(testLibId.ToString()));
            if (tempList != null)
            {
                QuestExt TtempList = new QuestExt();//获取试题集
                string whereclause = "I_LibID=" + testLibId;
                TList<TbTestLibOption> LibOptionList = new TestLibOptionDAO().GetByPage(whereclause, 0, 20);  //不会有超过20个选项的试题
                if (LibOptionList.Count > 0)
                {
                    TtempList.OptionList = LibOptionList;
                }
                TtempList.LibItem = tempList;
                return Json(TtempList, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return null;
            }
        }
        #endregion


        /// <summary>
        /// 学生提交练习
        /// </summary>
        /// <param name="ans"></param>
        /// <param name="praId"></param>
        /// <returns></returns>
        public int CompletePractice(string ans, int praId)
        {

            TestLibOptionDAO optinDao = new TestLibOptionDAO();
            int stuId = frontCurrentStu.GetUserID();//学生Id
            string stuCode = frontCurrentStu.GetNo();//学生学号
            string[] ansList = ans.Split(new char[] { ',' });
            //分离每个题目
            foreach (var item in ansList)
            {
                int isOk = 0;
                TbStuPracticeOptions sel = new TbStuPracticeOptions();
                //分离题目信息
                string[] titleInfor = item.Split(new char[] { ':' });
                //获取选项ID
                int opId = int.Parse(titleInfor[0]);
                sel.IStuId = stuId;
                sel.SStuCode = stuCode;
                sel.IOptionId = opId;//选项ID
                sel.ILibId = int.Parse(titleInfor[1]);//题目ID
                sel.IType = int.Parse(titleInfor[2]);//题目类型
                sel.IPracticeId = praId;
                TbTestLibOption opTmp = optinDao.GetByID(opId);
                if (opTmp != null)
                    isOk = (int)opTmp.IIsTrue;
                sel.IIsOk = isOk;
                selOption.Insert(sel);
            }

            //插入到题目信息表StuPracticeDetail中，统计分数
            if (InsertPracDetail(praId, stuId, stuCode))
            {
                int score = GetScorse(praId, stuId);
                if (score != 0)
                {
                    TbStuPractice stuTmp = stuPraDAO.GetByPage(
                        "I_StuID=" + stuId + " and I_PracticeID=" + praId, 0, int.MaxValue)[0];
                    stuTmp.IComplete = 1;
                    stuTmp.IScore = score;
                    stuPraDAO.Update(stuTmp);
                }
            }


            return 1;
        }
        /// <summary>
        /// 插入到题目详情表StuPracticeDetail
        /// </summary>
        /// <param name="praId"></param>
        /// <returns></returns>
        public bool InsertPracDetail(int praId, int stuId, string stuCode)
        {
            StuPracticeResultDAO praRes = new StuPracticeResultDAO();
            //获取当前练习题
            TbStuPracticeList pra = praListDAO.GetByID(praId);
            //得到当前练习题总分
            int totalScore = (int)pra.ITotal;
            int courseId = (int)pra.ICourseId;//课程ID
            int teaId = (int)pra.ITeaId;//教师ID
            //当期练习题目列表
            List<int> libIdList = new List<int>();
            //得到当前学生所做练习的选项
            string where = "I_PracticeID=" + praId + " and I_StuID=" + stuId;
            TList<TbStuPracticeOptions> optList = optionDAO.GetByPage(where, 0, int.MaxValue);
            //统计题目数量
            foreach (var item in optList)
            {
                int tmpId = (int)item.ILibId;
                if (libIdList.Contains(tmpId))
                    continue;
                else
                    libIdList.Add(tmpId);
            }
            //每到题的分数
            int score = (int)(totalScore / libIdList.Count);
            foreach (var item in optList)
            {
                int getSC = 0;//得分
                int libId = (int)item.ILibId;
                TbStuPracticeDetail deTmp = new TbStuPracticeDetail();
                deTmp.IStuId = stuId; deTmp.SStuCode = stuCode;
                deTmp.ILibId = libId;
                deTmp.ILibType = item.IType;
                deTmp.IPraId = item.IPracticeId;
                //若数组有此题ID，证明没有插入过
                if (libIdList.Contains(libId))
                {
                    int isTure = (int)item.IIsOk;
                    //做对即得分
                    if (isTure == 1)
                    {
                        getSC = score;

                    }
                    deTmp.IIsTrue = isTure;
                    deTmp.IScore = getSC;
                    detDAO.Insert(deTmp);
                    libIdList.Remove(libId);
                }
                else
                {
                    //多选题，一个选错，则全错
                    if (item.IIsOk == 0)
                    {
                        string whereC = "I_StuID=" + stuId + " and I_PraID=" + praId + " and I_LibID=" + libId;
                        try
                        {
                            TbStuPracticeDetail detmp1 = detDAO.GetByPage(whereC, 0, int.MaxValue)[0];
                            detmp1.IScore = 0;
                            detmp1.IIsTrue = 0;
                            detDAO.Update(detmp1);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                    //if END
                }
                //else END
            }
            //foreach END
            string resStr = "I_StuId=" + stuId + " and I_CourseId=" + courseId
                        + " and I_TeaId=" + teaId;
            TList<TbStuPracticeResult> resList = praRes.GetByPage(resStr, 0, int.MaxValue);
            if (resList.Count > 0)
            {
                TbStuPracticeResult stuRes = new TbStuPracticeResult();
                stuRes = resList[0];
                stuRes.IIncomplete -= 1;
                stuRes.IComplete += 1;
                praRes.Update(stuRes);
            }

            return true;
        }


        /// <summary>
        /// 取得学生成绩
        /// </summary>
        /// <param name="praId"></param>
        /// <param name="stuId"></param>
        /// <returns></returns>
        public int GetScorse(int praId, int stuId)
        {

            int score = 0;//学生得分
            string where = "I_PraID=" + praId + " and I_StuID=" + stuId;
            TList<TbStuPracticeDetail> deList = detDAO.GetByPage(where, 0, int.MaxValue);
            if (deList.Count > 0)
            {
                foreach (var item in deList)
                {
                    score += (int)item.IScore;
                }
                return score;
            }
            else
                return 0;
        }
    }
}
